package common.utils
{
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.text.TextField;
	import flash.utils.Timer;
	import flash.utils.getTimer;

	public class TimerCD
	{
		private var _initTime:uint;
		private var _coolDown:uint;
		private var _txt:TextField;
		private var _timer:Timer;
		private var _isStopClear:Boolean=false;

		public function get isStopClear():Boolean
		{
			return _isStopClear;
		}

		public function set isStopClear(value:Boolean):void
		{
			_isStopClear = value;
		}

		public function set coolDown(value:uint):void
		{
			_initTime = getTimer();
			_coolDown = value;
			_timer.start();
		}

		private var _callBack:Function;
		private var _txtType:String = "00:00";
		
		
		public function TimerCD(coolDown:uint,showTxt:TextField,callBack:Function,typeStr:String="00:00")
		{
			_coolDown = coolDown;
			_txt = showTxt;
			_initTime = getTimer();
			_callBack = callBack;
			_txtType = typeStr;
			_timer = new Timer(250);
			_timer.addEventListener(TimerEvent.TIMER,updateCoolDown);
			_timer.start();
			updateCoolDown();
		}
		public function get txtType():String
		{
			return _txtType;
		}
		
		public function set txtType(value:String):void
		{
			_txtType = value;
		}
		public function stop():void
		{
			_timer.stop();
		}
		private function updateCoolDown(event:Event=null):void{
			var t1:int = getTimer();
			var t2:int = _initTime+_coolDown*1000;
			var t3:int = int((t2-t1)/1000);
			var a:int = int(t3/60);
			var b:int = int(t3%60);
			_txt.text = "";
			if(a<0) a=0;
			if(b<0) b=0;
			var astr:String = a.toString();
			var bstr:String;
			if(b<10 && (_txtType=="00:00" || _txtType=="0:00" || _txtType=="00")){
				bstr = "0"+b;
			}else
			{
				bstr = String(b);
			}
			if(_txtType == "00:00")
			{
				if(a<10){
					astr = "0"+a;
				}else
				{
					astr = String(a);
				}
			}
			if(_txtType == "00" || _txtType == "0"){
				_txt.text = bstr;
			}else{
				_txt.text = astr+":"+bstr;
			}
			if(t3<=0)
			{
				if(_callBack != null)
				{
					_callBack();
				}
				_timer.stop();
				if(_isStopClear)
				{
					_txt = null;
					_callBack = null;
				}
			}
		}
	}
}